package top.yokey.shopnc.activity.home;

import android.content.Intent;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;

import com.squareup.otto.Subscribe;
import com.zhihu.matisse.Matisse;

import top.yokey.base.base.BaseLogger;
import top.yokey.base.util.ImageUtil;
import top.yokey.shopnc.base.BaseAnimClient;
import top.yokey.shopnc.base.BaseFileClient;
import top.yokey.shopnc.base.BaseImageLoader;
import top.yokey.shopnc.view.PullRefreshView;
import top.yokey.shopnc.R;
import top.yokey.shopnc.adapter.ChatOnlyListAdapter;
import top.yokey.shopnc.base.BaseApplication;
import top.yokey.shopnc.base.BaseConstant;
import top.yokey.shopnc.base.BaseCountTime;
import top.yokey.base.base.BaseHttpListener;
import top.yokey.base.base.BaseSnackBar;
import top.yokey.base.base.BaseToast;
import top.yokey.shopnc.base.SwipeActivity;
import top.yokey.base.bean.BaseBean;
import top.yokey.base.bean.ChatBean;
import top.yokey.base.bean.GoodsBean;
import top.yokey.base.event.MessageCountEvent;
import top.yokey.base.model.MemberChatModel;
import top.yokey.base.util.JsonUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author MapStory
 * @ qq 1002285057
 * @ Project https://gitee.com/MapStory/ShopNc-Android
 */

@ContentView(R.layout.activity_home_chat_only)
public class ChatOnlyActivity extends SwipeActivity {

    @ViewInject(R.id.mainRelativeLayout)
    private RelativeLayout mainRelativeLayout;
    @ViewInject(R.id.mainToolbar)
    private Toolbar mainToolbar;

    @ViewInject(R.id.mainPullRefreshView)
    private PullRefreshView mainPullRefreshView;

    @ViewInject(R.id.showImageView)
    private AppCompatImageView showImageView;
    @ViewInject(R.id.goodsRelativeLayout)
    private RelativeLayout goodsRelativeLayout;
    @ViewInject(R.id.goodsImageView)
    private AppCompatImageView goodsImageView;
    @ViewInject(R.id.goodsTextView)
    private AppCompatTextView goodsTextView;
    @ViewInject(R.id.moneyTextView)
    private AppCompatTextView moneyTextView;

    @ViewInject(R.id.imageImageView)
    private AppCompatImageView imageImageView;
    @ViewInject(R.id.contentEditText)
    private AppCompatEditText contentEditText;
    @ViewInject(R.id.sendTextView)
    private AppCompatTextView sendTextView;

    private boolean bottomBoolean;
    private GoodsBean goodsBean;
    private String memberIdString;
    private String goodsIdString;
    private String memberNameString;
    private String storeAvatarString;

    private ChatOnlyListAdapter mainAdapter;
    private ArrayList<ChatBean> mainArrayList;

    @Override
    public void initData() {

        memberIdString = getIntent().getStringExtra(BaseConstant.DATA_MEMBERID);
        goodsIdString = getIntent().getStringExtra(BaseConstant.DATA_GOODSID);

        if (TextUtils.isEmpty(memberIdString)) {
            BaseToast.get().showDataError();
            BaseApplication.get().finish(getActivity());
        }

        bottomBoolean = true;
        goodsBean = new GoodsBean();

        setToolbar(mainToolbar, "...");

        mainArrayList = new ArrayList<>();
        mainAdapter = new ChatOnlyListAdapter(mainArrayList, storeAvatarString);
        mainPullRefreshView.getRecyclerView().setAdapter(mainAdapter);
        mainPullRefreshView.setCanLoadMore(false);
        mainPullRefreshView.setCanRefresh(false);

        if (TextUtils.isEmpty(goodsIdString)) {
            showImageView.setVisibility(View.GONE);
            goodsRelativeLayout.setVisibility(View.GONE);
        }

        getInfo();

    }

    @Override
    public void initEven() {

        showImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goodsRelativeLayout.getVisibility() == View.GONE) {
                    goodsRelativeLayout.setVisibility(View.VISIBLE);
                    BaseAnimClient.get().showAlpha(goodsRelativeLayout);
                } else {
                    goodsRelativeLayout.setVisibility(View.GONE);
                    BaseAnimClient.get().goneAlpha(goodsRelativeLayout);
                }
            }
        });

        imageImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.get().startMatisse(getActivity(), 1, BaseConstant.CODE_ALBUM);
            }
        });

        sendTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendMessage();
            }
        });

        mainPullRefreshView.getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                bottomBoolean = false;
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();
                    if (lastVisibleItem == (totalItemCount - 1)) {
                        bottomBoolean = true;
                    }
                }
            }
        });

        contentEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bottomBoolean) {
                    new BaseCountTime(200, 50) {
                        @Override
                        public void onFinish() {
                            super.onFinish();
                            setRecyclerView();
                        }
                    }.start();
                }
            }
        });

        mainAdapter.setOnItemClickListener(new ChatOnlyListAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, ChatBean chatBean) {

            }
        });

    }

    @Override
    public void onActivityResult(int req, int res, Intent intent) {
        super.onActivityResult(req, res, intent);
        if (res == RESULT_OK) {
            switch (req) {
                case BaseConstant.CODE_ALBUM:
                    updateImage(Matisse.obtainPathResult(intent).get(0));
                    break;
                default:
                    break;
            }
        }
    }

    //自定义方法

    private void getInfo() {

        MemberChatModel.get().getNodeInfo(memberIdString, goodsIdString, new BaseHttpListener() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                try {
                    BaseLogger.get().show(baseBean.getDatas());
                    JSONObject jsonObject = new JSONObject(baseBean.getDatas());
                    JSONObject storeJsonObject = new JSONObject(jsonObject.getString("user_info"));
                    memberNameString = storeJsonObject.getString("member_name");
                    storeAvatarString = storeJsonObject.getString("store_avatar");
                    if (jsonObject.has("chat_goods")) {
                        goodsBean = JsonUtil.json2Bean(jsonObject.getString("chat_goods"), GoodsBean.class);
                        BaseImageLoader.get().display(goodsBean.getPic36(), goodsImageView);
                        goodsTextView.setText(goodsBean.getGoodsName());
                        moneyTextView.setText("￥");
                        moneyTextView.append(goodsBean.getGoodsPrice());
                    }
                    mainAdapter = new ChatOnlyListAdapter(mainArrayList, storeAvatarString);
                    mainPullRefreshView.getRecyclerView().setAdapter(mainAdapter);
                    setToolbar(mainToolbar, storeJsonObject.getString("store_name"));
                    getMessage();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String reason) {
                BaseSnackBar.get().show(mainRelativeLayout, reason);
                new BaseCountTime(BaseConstant.TIME_COUNT, BaseConstant.TIME_TICK) {
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        getInfo();
                    }
                }.start();
            }
        });

    }

    private void getMessage() {

        MemberChatModel.get().getChatLog(memberIdString, new BaseHttpListener() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                mainArrayList.clear();
                String data = JsonUtil.getDatasString(baseBean.getDatas(), "list");
                mainArrayList.addAll(JsonUtil.json2ArrayList(data, ChatBean.class));
                Collections.reverse(mainArrayList);
                mainPullRefreshView.setComplete();
                if (bottomBoolean) {
                    setRecyclerView();
                }
            }

            @Override
            public void onFailure(String reason) {
                BaseSnackBar.get().show(mainRelativeLayout, reason);
                new BaseCountTime(BaseConstant.TIME_COUNT, BaseConstant.TIME_TICK) {
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        getMessage();
                    }
                }.start();
            }
        });

    }

    private void sendMessage() {

        String message = contentEditText.getText().toString();

        if (TextUtils.isEmpty(message)) {
            BaseSnackBar.get().show(mainRelativeLayout, "请输入消息！");
            return;
        }

        sendTextView.setEnabled(false);
        sendTextView.setText("发送中...");

        MemberChatModel.get().sendMessage(memberIdString, memberNameString, message, goodsIdString, new BaseHttpListener() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                contentEditText.setText("");
                String data = JsonUtil.getDatasString(baseBean.getDatas(), "msg");
                ChatBean chatBean = JsonUtil.json2Bean(data, ChatBean.class);
                mainArrayList.add(chatBean);
                mainPullRefreshView.setComplete();
                sendTextView.setEnabled(true);
                sendTextView.setText("发 送");
                setRecyclerView();
            }

            @Override
            public void onFailure(String reason) {
                BaseSnackBar.get().show(mainRelativeLayout, reason);
                sendTextView.setEnabled(true);
                sendTextView.setText("发 送");
            }
        });

    }

    private void setRecyclerView() {

        mainPullRefreshView.getRecyclerView().smoothScrollToPosition(mainArrayList.size());

    }

    private void updateImage(String path) {

        BaseSnackBar.get().showHandler(mainRelativeLayout);

        MemberChatModel.get().imageSend(BaseFileClient.get().createImage("chat_only", ImageUtil.getLocal(path)), new BaseHttpListener() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                try {
                    JSONObject jsonObject = new JSONObject(baseBean.getDatas());
                    String url = jsonObject.getString("url");
                    url = "[SIMG:" + url + "]";
                    contentEditText.setText(url);
                    sendMessage();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                BaseLogger.get().show(baseBean.getDatas());
            }

            @Override
            public void onFailure(String reason) {
                BaseSnackBar.get().show(mainRelativeLayout, reason);
            }
        });

    }

    @Subscribe
    @SuppressWarnings("unused")
    public void onMessageCountEvent(MessageCountEvent event) {

        getMessage();

    }

}
